package xyz.zdsoft.ask_for_leave_manage_module.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import xyz.zdsoft.ask_for_leave_manage_module.bo.LeaveBo;
import xyz.zdsoft.ask_for_leave_manage_module.mapper.StudentLeavesMapper;
import xyz.zdsoft.ask_for_leave_manage_module.service.StudentLeaveService;
import xyz.zdsoft.ask_for_leave_manage_module.vo.*;
import xyz.zdsoft.common.entity.Leave;
import xyz.zdsoft.common.entity.LeaveOperationRecord;
import xyz.zdsoft.common.exception.BizException;
import xyz.zdsoft.common.service.impl.LeaveServiceImpl;
import xyz.zdsoft.common.utils.JwtUtils;
import xyz.zdsoft.common.utils.Result;
import xyz.zdsoft.common.utils.ResultBody;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author 夏兵
 */
@Service
public class StudentLeaveServiceImpl extends ServiceImpl<StudentLeavesMapper, LeaveVo> implements StudentLeaveService {

    @Autowired
    private StudentLeavesMapper studentLeavesMapper;

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private LeaveServiceImpl leaveService;

    @Override
    public Result<LeaveVo> queryCurStuLeaves(LeaveBo leaveBo) {
        Page<Leave> page;
        if (leaveBo.getCurrent() != null && leaveBo.getSize() != null) {
            page = new Page<>(leaveBo.getCurrent(), leaveBo.getSize());
        } else {
            page = new Page<>();
        }
        int stuId;
        try {
            stuId = Integer.parseInt(JwtUtils.getMemberIdByJwtToken(request));
        } catch (NullPointerException e) {
            throw new BizException("401", "请登录后操作");
        }
        QueryWrapper<Leave> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("student_id", stuId);
        queryWrapper.ge(leaveBo.getStartLeaveTime() != null, "submit_time", leaveBo.getStartLeaveTime());
        queryWrapper.le(leaveBo.getEndLeaveTime() != null, "submit_time", leaveBo.getEndLeaveTime());
        queryWrapper.eq(leaveBo.getStatus() != null, "status", leaveBo.getStatus());
        queryWrapper.eq(leaveBo.getLeaveType() != null, "leave_type", leaveBo.getLeaveType());
        queryWrapper.like(leaveBo.getTheme() != null, "theme", leaveBo.getTheme());
        queryWrapper.orderByDesc("submit_time");
        return Result.ok().data(leaveService.page(page, queryWrapper));
    }

    @Override
    public Result<CurStuLeaveBaseInfoVo> queryCurStuBaseInfo() {
        int stuId;
        try {
            stuId = Integer.parseInt(JwtUtils.getMemberIdByJwtToken(request));
        } catch (NullPointerException e) {
            throw new BizException("401", "请登录后操作");
        }
        return Result.ok().data(studentLeavesMapper.queryCurStuBaseInfo(stuId));
    }

    @Override
    public Result<String> queryFailReasonByLeaId(Integer leaveId) {
        return Result.ok().data(studentLeavesMapper.queryFailReasonByLeaId(leaveId));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultBody askForLeave(LeaveBo leaveBo) {
        Leave leave = new Leave();
        boolean tag = true;
        // 存在就是修改请假
        if (leaveBo.getId() != null) {
            leave.setId(leaveBo.getId());
            tag = false;
        }
        int stuId;
        try {
            stuId = Integer.parseInt(JwtUtils.getMemberIdByJwtToken(request));
        } catch (NullPointerException e) {
            throw new BizException("401", "请登录后操作");
        }
        leave.setStudentId(stuId);
        if (tag && leaveBo.getLeaveType() == null) {
            return ResultBody.error("请假类型不能为空");
        }
        leave.setLeaveType(leaveBo.getLeaveType());
        // 默认申请是审批中
        leave.setStatus(0);
        if (tag && StringUtils.isBlank(leaveBo.getTheme())) {
            return ResultBody.error("请假主题不能为空");
        }
        leave.setTheme(leaveBo.getTheme());
        if (tag && leaveBo.getStartLeaveTime() == null) {
            return ResultBody.error("请假开始时间不能为空");
        }
        leave.setStartLeaveTime(leaveBo.getStartLeaveTime());
        if (tag && leaveBo.getEndLeaveTime() == null) {
            return ResultBody.error("请假结束时间不能为空");
        }
        leave.setEndLeaveTime(leaveBo.getEndLeaveTime());
        if (tag && leaveBo.getStartLeaveTime() != null && leaveBo.getEndLeaveTime() != null
                && leaveBo.getStartLeaveTime().getTime() >= leaveBo.getEndLeaveTime().getTime()) {
            return ResultBody.error("请假开始时间必须小于请假结束时间");
        }
        if (tag && StringUtils.isBlank(leaveBo.getReason())) {
            return ResultBody.error("请假原因不能为空");
        }
        leave.setReason(leaveBo.getReason());
        leave.setSubmitTime(new Date());
        leaveService.saveOrUpdate(leave);

        LeaveOperationRecord record = new LeaveOperationRecord();
        System.out.println(leave.getId());
        record.setLeaveId(leave.getId());
        // 默认申请是审批中
        record.setStatus(0);
        record.setOperationTime(new Date());
        studentLeavesMapper.insertLeaveLog(record);
        return ResultBody.success();
    }

    @Override
    public Result<LeaveRecords> queryCurStuLeaveRecords(Integer leaveId) {
        if (leaveId == null) {
            throw new BizException("请假id不能为空");
        }
        int stuId;
        try {
            stuId = Integer.parseInt(JwtUtils.getMemberIdByJwtToken(request));
        } catch (NullPointerException e) {
            throw new BizException("401", "请登录后操作");
        }
        return Result.ok().data(studentLeavesMapper.queryCurStuLeaveRecords(stuId, leaveId));
    }

    @Override
    public Result<StuLeaveDetailVo> queryLeaveDetailByLeaId(Integer leaveId) {
        if (leaveId == null) {
            throw new BizException("请假id不能为空");
        }
        Leave leave = leaveService.getById(leaveId);
        if (leave == null) {
            throw new BizException("找不到该条请假记录");
        }
        return Result.ok().data(new StuLeaveDetailVo(leave.getId(), leave.getTheme(), leave.getStartLeaveTime(),
                leave.getEndLeaveTime(), leave.getLeaveType(), leave.getReason()));
    }

    @Override
    public Result<StuLeaveAttachVo> queryStuLeaveAttach(Integer leaveId) {
        if (leaveId == null) {
            throw new BizException("请假id不能为空");
        }
        return Result.ok().data(studentLeavesMapper.queryStuLeaveAttach(leaveId));
    }

    @Override
    public Integer insertLeaveLog(LeaveOperationRecord record) {
        return studentLeavesMapper.insertLeaveLog(record);
    }
}
